package com.wujilin.okra.fragment;

import static android.widget.Toast.LENGTH_SHORT;
import static com.wujilin.okra.Okra.EXTRA_CATEGORY_ID;
import static com.wujilin.okra.Okra.EXTRA_LOADER_ID;
import static com.wujilin.okra.Okra.EXTRA_OKR_LIST_TITLE;
import static com.wujilin.okra.Okra.LOADER_CATEGORY_LIST;
import static com.wujilin.okra.Okra.LOADER_OKRA_LIST;
import static com.wujilin.okra.Okra.LOADER_OKRA_LIST_BY_CATEGORY;
import static com.wujilin.okra.Okra.REQUEST_CATEGORY_DELETE;
import static com.wujilin.okra.Okra.REQUEST_CATEGORY_NEW;
import static com.wujilin.okra.Okra.TAG_DIALOG_CATEGORY_DELETE;
import static com.wujilin.okra.Okra.TAG_DIALOG_CATEGORY_EDIT;
import static com.wujilin.okra.Okra.TAG_DIALOG_OBJECTIVE_NEW;
import static com.wujilin.okra.Okra.TAG_HOME;
import android.app.Activity;
import android.app.ListFragment;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.wujilin.okra.R;
import com.wujilin.okra.adapter.CategoryListAdapter;
import com.wujilin.okra.database.ModelCursor;
import com.wujilin.okra.loader.QueryCursorLoader;

/**
 * @author Belin Wu
 */
public class CategoryListFragment extends ListFragment implements LoaderCallbacks<Cursor> {
	private Callback callback;
	
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		callback = (Callback) activity;
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getLoaderManager().initLoader(LOADER_CATEGORY_LIST, null, this);
    }
    
	@Override
	@SuppressWarnings("unchecked")
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    	switch (requestCode) {
	    	case REQUEST_CATEGORY_DELETE:
	    		LoaderCallbacks<Cursor> callback = (LoaderCallbacks<Cursor>) getFragmentManager().findFragmentByTag(TAG_HOME);
	    		if (callback != null) {
	    			getLoaderManager().restartLoader(LOADER_OKRA_LIST, null, callback);
	    		}
	    	case REQUEST_CATEGORY_NEW:
	    		getLoaderManager().restartLoader(LOADER_CATEGORY_LIST, null, this);
	    		break;
    	}
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    	View view = super.onCreateView(inflater, container, savedInstanceState);
    	ListView listView = (ListView) view.findViewById(android.R.id.list);
    	registerForContextMenu(listView);
    	return view;
    }
    
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    	getActivity().getMenuInflater().inflate(R.menu.fragment_category_list_context, menu);
    }
    
    @Override
    public boolean onContextItemSelected(MenuItem item) {
    	AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
		long categoryId = info.id;
    	switch (item.getItemId()) {
	    	case R.id.edit_category: {
	    		String category = ((ModelCursor) getListAdapter().getItem(info.position)).getModel().getString("name");
	    		CategoryEditFragment fragment = CategoryEditFragment.newInstance(categoryId, category);
	    		fragment.show(getFragmentManager(), TAG_DIALOG_CATEGORY_EDIT);
	    		break;
	    	}
	    	case R.id.add_okra: {
	    		ObjectiveNewFragment fragment = new ObjectiveNewFragment();
	    		Bundle args = new Bundle();
	    		args.putLong(EXTRA_CATEGORY_ID, categoryId);
	    		fragment.setArguments(args);
				fragment.show(getFragmentManager(), TAG_DIALOG_OBJECTIVE_NEW);
	    		break;
	    	}
	    	case R.id.delete:
	    		CategoryDeleteFragment fragment = CategoryDeleteFragment.newInstance(categoryId);
	    		fragment.show(getFragmentManager(), TAG_DIALOG_CATEGORY_DELETE);
	    		fragment.setTargetFragment(this, REQUEST_CATEGORY_DELETE);
	    		break;
			default:
				return super.onContextItemSelected(item);
    	}
    	return true;
    }
    
    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
    	TextView countText = (TextView) v.findViewById(R.id.category_count);
    	TextView nameText = (TextView) v.findViewById(R.id.category_name);
    	int count = Integer.valueOf(countText.getText().toString());
    	if (count <= 0) {
    		Toast.makeText(getActivity(), R.string.no_okras, LENGTH_SHORT).show();
    		return;
    	}
    	Intent intent = new Intent();
    	intent.putExtra(EXTRA_CATEGORY_ID, id);
    	intent.putExtra(EXTRA_OKR_LIST_TITLE, nameText.getText().toString());
    	intent.putExtra(EXTRA_LOADER_ID, LOADER_OKRA_LIST_BY_CATEGORY);
    	callback.onViewOkraList(intent);
    }

	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle args) {
		String sql = "select c._id, c.name, sum(case when o._id is null then 0 else 1 end) count from category c left join objective o on c._id=o.category_id group by c._id";
   		return new QueryCursorLoader(getActivity(), sql);
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
		ListAdapter adapter = new CategoryListAdapter(getActivity(), (ModelCursor) data);
		setListAdapter(adapter);
	}

	@Override
	public void onLoaderReset(Loader<Cursor> loader) {
		((CategoryListAdapter) getListAdapter()).changeCursor(null);
	}
	
	public static interface Callback {
		void onViewOkraList(Intent intent);
	}
}
